const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 创建验证码记录
  async createVerificationCode(phone, code) {
    // 先删除旧的验证码
    await db.execute(
      'DELETE FROM sms_codes WHERE phone = ?',
      [phone]
    );
    
    // 添加新验证码
    const [result] = await db.execute(
      'INSERT INTO sms_codes (phone, code, expires_at) ' +
      'VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE))',
      [phone, code]
    );
    
    return result.affectedRows > 0;
  },

  // 验证验证码
  async verifyCode(phone, code) {
    const [codes] = await db.execute(
      'SELECT * FROM sms_codes WHERE phone = ? AND code = ? AND expires_at > NOW()',
      [phone, code]
    );
    
    if (codes.length === 0) {
      return false;
    }
    
    // 验证成功后删除验证码
    await db.execute(
      'DELETE FROM sms_codes WHERE phone = ?',
      [phone]
    );
    
    return true;
  }
};